﻿/*******************************************************************************
 * Copyright © 2016-2020 北京网非科技有限公司 版权所有
 * Author: 北京网非科技有限公司
 * Description: 网非快速开发平台NET
 * Website：http://www.wfdot.com
*********************************************************************************/
using CubicFWNet.Common;
using CubicFWNet.Data.SystemManage;
using CubicFWNet.Data.SystemManage.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CubicFWNet.Application.SystemManage
{
    public class UserApp
    {
        private UserRepository service;
        private RoleRepository _roleRepository;
        private RelevanceRepository _relevanceRepository;
        public UserApp()
        {
            service = new UserRepository();
            _roleRepository = new RoleRepository();
            _relevanceRepository = new RelevanceRepository();
        }

        public ResponseResult Delete(Guid id)
        {
            var del = service.FindEntity(id);
            if (del == null)
                return new ResponseResult { Status = ResultType.error.ToString(), Message = "未找到该数据", Data = id };
            _relevanceRepository.DeleteBy("UserRole", id);
            _relevanceRepository.DeleteBy("UserModule", id);
            service.Delete(del);
            return new ResponseResult { Status = ResultType.success.ToString(), Data = id };
        }

        public User GetForm(Guid id)
        {
            return service.FindEntity(id);
        }

        public IEnumerable<User> GetList(string keyWord,bool isSystem)
        {
            var expression = ExtLinq.True<User>();
            expression = expression.And(t => isSystem || t.UserName != "admin");
            if (!string.IsNullOrEmpty(keyWord))
            {
                expression = expression.And(t => t.FamilyName.Contains(keyWord));
            }
            return service.IQueryable(expression).OrderByDescending(u => u.SortNo);  
        }

        /// <summary>
        /// 检查账号和密码是否正确
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>ResponseResult.Result:User</returns>
        public ResponseResult CheckLogin(string username, string password)
        {
            User user = service.FindEntity(t => t.UserName == username);
            if (user != null)
            {
                if (user.Status)
                {
                    if (PasswordHash.ValidatePassword(password, user.Password))
                    {
                        return new ResponseResult { Status = LoginResult.success.ToString(), Data = user, Message = "登录成功" };
                    }
                    else
                    {
                        return new ResponseResult { Status = LoginResult.password_error.ToString(), Message = "用户名或者密码不正确，请重新输入", Data = user };
                    }
                }
                else
                {
                    return new ResponseResult { Status = LoginResult.error.ToString(), Message = "账户被系统锁定，请联系管理员", Data = user };
                }
            }
            else
            {
                return new ResponseResult { Status = LoginResult.error.ToString(), Message = "用户名或者密码不正确，请重新输入" };
            }
        }

        public void AddOrUpdate(User user, string[] roleIds, string[] moduleIds)
        {
            user.Password = PasswordHash.CreateHash(user.Password);
            if (user.Id == Guid.Empty)
            {
                if (service.IsExist(u => u.UserName == user.UserName))
                {
                    throw new Exception("用户账号已存在");
                }
                user.Id = Guid.NewGuid();
                service.Insert(user);
            }
            else
            {
                service.Update(user);
            }
            //更新用户的角色
            var type = "UserRole";
            _relevanceRepository.DeleteBy(type, user.Id);
            var secIds = roleIds.Where(a => !string.IsNullOrWhiteSpace(a)).Select(a => Guid.Parse(a)).ToArray();
            _relevanceRepository.AddRelevance(type, secIds.ToLookup(u => user.Id));

            //更新用户的模块
            type = "UserModule";
            _relevanceRepository.DeleteBy(type, user.Id);
            secIds = moduleIds.Where(a => !string.IsNullOrWhiteSpace(a)).Select(a => Guid.Parse(a)).ToArray();
            _relevanceRepository.AddRelevance(type, secIds.ToLookup(u => user.Id));

        }


        /// <summary>
        /// 加载一个角色全部用户
        /// </summary>
        public IEnumerable<User> Load(Guid roleId, int pageindex, int pagesize)
        {
            if (pageindex < 1) pageindex = 1;  //TODO:如果列表为空新增加一个用户后，前端会传一个0过来，奇怪？？
            IEnumerable<User> users;
            int records = 0;
            if (roleId == Guid.Empty)
            {
                users = service.LoadUsers(pageindex, pagesize);
                records = service.Count();
            }
            else
            {
                users = service.LoadInRole(pageindex, pagesize, roleId);
                records = service.GetUserCntInRole(roleId);
            }
            return users;
        }


        /// <summary>
        /// 加载一个用户的全部 角色Ids
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<Guid> LoadRole(Guid userId)
        {
            List<Guid> modules = new List<Guid>();
            if (userId == Guid.Empty)
            {
                return modules;
            }
            return _relevanceRepository.LoadByUser(userId).ToList();
        }


    }
}
